package com.wframe.project.jnd.wx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.util.DateConvert;
import com.wframe.framework.spring.SpringContextHolder;
import com.wframe.project.jnd.entity.Integral;
import com.wframe.project.jnd.entity.Promotion;
import com.wframe.project.jnd.rest.util.*;
import com.wframe.project.jnd.services.*;
import com.wframe.project.jnd.util.WebUtils;
import com.wframe.project.jnd.vo.IntegralRulesVo;
import com.wframe.project.jnd.vo.PriceBeanVo;
import com.wframe.project.jnd.vo.UrgentProduct;
import org.apache.commons.codec.binary.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/4/19.
 */
@RequestMapping("/we/home")
@Controller
public class WeHomeController {

    @Autowired
    CouponService couponService;

    @Autowired
    UserService userService;

    @Autowired
    OrderService orderService;

    @Autowired
    ProductService productService;

    @Autowired
    InformationService informationService;
    @Autowired
    IntegralService integralService;

    private static final String WE_INTEGRAL_RULE = "WE_INTEGRAL_RULE";

    @RequestMapping("index")
    public String index(HttpServletRequest request, Model model) throws Exception {

        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return "redirect:/we/user/login";
        } else {
            String userid = WebSession.getWbUser(request.getSession()).getUserid();
//            JdataBean user = userService.getUser(userid);
            JdataBean wbuser = userService.getquerywbuser(userid);
            model.addAttribute("ordernum", orderService.statStatusNum(userid));
            model.addAttribute("usernum", userService.statUserPro(userid, UserService.UserSourceEnum.WECHAT.ordinal()).getDataMap());
//            model.addAttribute("user", user.getDataMap());
            model.addAttribute("wbuser", wbuser.getDataMap());
        }
        return "/wesite/view/home/my";
    }


    @RequestMapping("my-coupon")
    public String myCoupon(HttpServletRequest request, Model model) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/we/user/login";
        }
        PageResult pr = couponService.queryCoupon(WebSession.getWbUser(request.getSession()).getUserid(), 1, UserService.UserSourceEnum.WECHAT.ordinal(), 1, 1);
        model.addAttribute("count", pr.getResultCount());
        model.addAttribute("user", userService.getUser(WebSession.getWbUser(request.getSession()).getUserid()).getDataMap());
        return "/wesite/view/home/my-coupon";
    }

    @RequestMapping("my-coupon-list")
    public void myCouponList(Integer state, String psize, String pno, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        JsonReturn json = new JsonReturn();
        JdataBean data = new JdataBean();
        if (!WebSession.checkLoginStatus(request.getSession())) {
            data.put("login", "no");
            data.put("list", new ArrayList());
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
            return;
        } else {
            data.put("login", "yes");
        }
        int pagesize = 10;
        int pageno = 1;
        if (StringUtils.isNotBlank(psize)) {
            pagesize = Integer.parseInt(psize);
        }
        if (StringUtils.isNotBlank(pno)) {
            pageno = Integer.parseInt(pno);
        }
        PageResult pr = couponService.queryCoupon(WebSession.getWbUser(request.getSession()).getUserid(), state, UserService.UserSourceEnum.WECHAT.ordinal(), pagesize, pageno);
        String userid = WebSession.getWbUser(request.getSession()).getUserid();
        List<JdataBean> count = couponService.countCoupon(userid);
        String usableCount = couponService.getUsableCount(userid,2);
        data.put("list", pr.getList());
        data.put("count",count);
        data.put("usableSize",usableCount);
        json.putData(data);
        WebUtils.responseWrite(response, json.toString());
    }

    /**
     * 进入可领取优惠券页面
     */
    @RequestMapping(value = "usable")
    public String loginUsableCount (HttpSession session) {
        if (!WebSession.checkLoginStatus(session)) {
            return "/wesite/view/sign/login";
        }else {
            return "/wesite/view/home/get-coupon";
        }
    }

    /**
     * 获取可领取优惠券数据
     */
    @RequestMapping("getUsable")
    public void getUsableCountList (String page_pno,HttpSession session, HttpServletRequest request, HttpServletResponse response) {

        JsonReturn json = new JsonReturn();
        if (!WebSession.checkLoginStatus(request.getSession())) {
            WebUtils.responseWrite(response, json.toErrorString(getClass(), new ClientException(CodeEnum.LoginOut)));
            return;
        }
        int size = 6;
        int pno = 1;
        if (StringUtils.isNotBlank(page_pno)) pno = Integer.parseInt(page_pno);
        JdataBean parms = new JdataBean();
        parms.put("userid",WebSession.getWbUser(request.getSession()).getUserid());
        parms.put("source",2);
        PageResult pr = couponService.getUsableCoupon(parms,size,pno);
        JdataBean data = new JdataBean();
        data.put("list",pr.getList());
        json.putData(data);
        WebUtils.responseWrite(response, json.toString());
    }


//    @RequestMapping("my-coupon-add")
//    public void myCouponAdd(HttpServletResponse response) {
//        JsonReturn json = new JsonReturn();
//        try {
//            WebUtils.responseWrite(response, json.toString());
//        } catch (Exception e) {
//            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
//        }
//    }


    /**
     * 常购清单
     *
     * @param like
     * @param pno
     * @return
     */
    @RequestMapping(value = "oftenList")
    public String oftenList(Model model, String like, String pno, HttpSession session) {
        if (!WebSession.checkLoginStatus(session)) {
            return "/wesite/view/sign/login";
        }
        int pagesize = 100;
        int pageno = 1;
        if (StringUtils.isNotBlank(pno)) {
            pageno = Integer.parseInt(pno);
        }
        JdataBean parm = new JdataBean();
        parm.put("userid", WebSession.getWbUser(session).getUserid());
        parm.put("like", like);


        PageResult pr = orderService.queryOften(parm, pagesize, pageno);
        List<Map> list = pr.getList();
        for (Map bean : list) {
            Object o = bean.get("productid");
            boolean can = productService.getControlsales(WebSession.getWbUser(session).getUserid(), o.toString());
            bean.put("can", can);
        }
        model.addAttribute("list", pr.getList());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        model.addAttribute("like", like);
        return "/wesite/view/home/always-buy";
    }

    /**
     * 全选，单选删除商品
     */

    @RequestMapping(value = "/delOften")
    public void delOften(@RequestParam("ids[]") String[] ids, HttpSession session, HttpServletResponse response) {


        JsonReturn json = new JsonReturn();
        try {

            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            for (int i = 0; i < ids.length; i++) {
                orderService.delOften(WebSession.getWbUser(session).getUserid(), ids[i]);
            }

            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 添加到购物车
     *
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addToCart")
    @ResponseBody
    public String addToCart(@RequestParam("idsAmounts[]") String[] idsAmounts, HttpSession session) throws Exception {
       /* JsonReturn json = new JsonReturn();

        SessionUser sessionUser = WebSession.getWbUser(request.getSession());
        if (sessionUser == null) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), new ClientException(CodeEnum.LoginOut)));
            return;
        }

        if (!WebSession.checkWbUserAuth(request.getSession())) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), new ClientException(CodeEnum.NoAuth)));
            return;
        }
        List<PriceBeanVo> prices = new ArrayList<PriceBeanVo>();
        int sumAmount = 0;
        int errCode = 1;

        for (int i = 0; i < idsAmounts.length; i++) {
            String[] arridAmount = idsAmounts[i].split("_");
            String id = arridAmount[0];
            int amount = Integer.parseInt(
                    arridAmount[1]);
            sumAmount += amount;
            prices.add(new PriceBeanVo(id, amount));
        }
        List<Map> errs = orderService.checkStock(prices);//库存检查
        if (errs.size() > 0) throw new ClientException(CodeEnum.INVENTORY_SHORTAGE.getName(), CodeEnum.INVENTORY_SHORTAGE.getCode());
        errs = orderService.checkProductstatus(prices);//商品状态检查
        if (errs.size() > 0) throw new ClientException(CodeEnum.NO_SALES.getName(), CodeEnum.NO_SALES.getCode());

        for (PriceBeanVo price : prices) {
            JdataBean product = productService.getProductInfo(price.getPriceId());
            if (product.getInt("iscontrol") != 0) {
                if (!productService.getControlsales(WebSession.getWbUser(request.getSession()).getUserid(), product.getString("id"))) {
                    throw new ClientException(CodeEnum.OUT_CONTROL_AREA);
                }
            }
            if (price.getBuyNum() <= 0) {
                throw new ClientException(CodeEnum.PURCHASE_QUANTITY_ERROR);
            }
        }
        for (PriceBeanVo price : prices) {
            JdataBean product = productService.getProductInfo(price.getPriceId());
            orderService.addToCart(WebSession.getWbUser(request.getSession()).getUserid(), product.getString("id"), price.getPriceId(), price.getBuyNum());
            product.put("amount", price.getBuyNum());
            model.addAttribute("bean", product.getDataMap());
        }

        WebUtils.responseWrite(response, json.toString());*/
        JsonReturn json = new JsonReturn();
        List<PriceBeanVo> prices = new ArrayList<>();
        for (int i = 0; i < idsAmounts.length; i++) {
            String[] arridAmount = idsAmounts[i].split("_");
            String id = arridAmount[0];
            int amount = Integer.parseInt(arridAmount[1]);
            //购买商品数量为负数
            if (amount <= 0) {
                return json.toErrorString(this.getClass(), new ClientException(CodeEnum.PURCHASE_QUANTITY_ERROR));
            }
            prices.add(new PriceBeanVo(id, amount));
        }

        String userid = WebSession.checkUserAuth(session);
        Map<String, List<UrgentProduct>> errs = orderService.checkProducts(userid, prices, Promotion.Platform.WE.ordinal());//商品检查
        Set<Map.Entry<String, List<UrgentProduct>>> entries = errs.entrySet();
        Iterator<Map.Entry<String, List<UrgentProduct>>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<UrgentProduct>> next = iterator.next();
            String type = next.getKey();
            List<UrgentProduct> err = next.getValue();
            if (!err.isEmpty()) {
                return json.toErrorString(this.getClass(), new ClientException(JSON.toJSONString(err), type));
            }
        }

        for (PriceBeanVo price : prices) {
            orderService.addToCart(userid, price.getPriceId(), price.getPriceId(), price.getBuyNum());
        }

        return json.toString();
    }

    /**
     * 进入我的积分页面
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("integral")
    public String integral(HttpServletRequest request, Model model) throws Exception {

        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return "redirect:/we/user/login";
        }
        String userid = WebSession.getWbUser(request.getSession()).getUserid();
        List<JdataBean> data = integralService.queryWXIntegralList(userid);
        List<Map<String,Object>> integralList = new ArrayList<>();
        for(JdataBean bean : data) {
            integralList.add(bean.getDataMap());
        }
        model.addAttribute("integrals",integralList);
        JdataBean myIntegral = integralService.queryUserIntegrals(userid);
        model.addAttribute("myIntegral",myIntegral.getDataMap());

        return "/wesite/view/home/my-integral";
    }

    @RequestMapping("integral-center")
    public String integralCenter(HttpServletRequest request, Model model) throws Exception {

        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return "redirect:/we/user/login";
        }
        String userid = WebSession.getWbUser(request.getSession()).getUserid();
        JdataBean myIntegral = integralService.queryUserIntegrals(userid);
        model.addAttribute("myIntegral",myIntegral.getDataMap());

        //查询可兑换的优惠卷
        List<JdataBean> couponData = integralService.queryExchangeCoupon();
        List<Map<String, Object>> couponList = new ArrayList<>();
        for (JdataBean coupon : couponData) {
            couponList.add(coupon.getDataMap());
        }
        model.addAttribute("couponList", couponList);
        //查询积分规则
        JdataBean rule = integralService.getIntegralRules();
        if(rule != null) {
            List<Integer> days = (List<Integer>) rule.get("days");
            Map<Integer, Integer> days_integral = (Map<Integer, Integer>)rule.get("days_integrals");
            String integral_rule = "";
            try {
                StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
                if (stringRedisTemplate != null && stringRedisTemplate.opsForValue().get(WE_INTEGRAL_RULE) != null) {
                    String data = StringUtils.trimToEmpty(stringRedisTemplate.opsForValue().get(WE_INTEGRAL_RULE));
                    integral_rule = SerializationUtils.deserialize(org.apache.commons.codec.binary.Base64.decodeBase64(data));
                } else {
                    StringBuffer sb = new StringBuffer("每日签到可获得");
                    String integral_totay = rule.getString("integral_today");
                    sb.append(integral_totay).append("积分");
                    for (int i = 0 ; i < days.size() ; i++) {
                        sb.append(",累计").append(days.get(i)).append("日连续签到可获得额外获得")
                                .append(days_integral.get(days.get(i))).append("积分");
                    }
                    sb.append("；连续7日签到后重新计算累计天数。");
                    integral_rule = sb.toString();
                    String data = org.apache.commons.codec.binary.Base64.encodeBase64String(SerializationUtils.serialize(integral_rule));
                    stringRedisTemplate.opsForValue().set(WE_INTEGRAL_RULE, data, 2, TimeUnit.MINUTES);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            model.addAttribute("integral_rule", integral_rule);
            model.addAttribute("days", rule.get("days"));
            model.addAttribute("integral_today", rule.get("integral_today"));
            model.addAttribute("days_integrals" , JSON.toJSON(days_integral));
        }

        return "/wesite/view/home/integral-center";
    }

    @RequestMapping(value = "exchangeCoupon")
    @ResponseBody
    public String exchangeCoupon(HttpServletRequest request, String couponid,
                                 HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        if (!WebSession.checkLoginStatus(request.getSession())) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), new ClientException(CodeEnum.LoginOut)));
            return null;
        }
        String userid = WebSession.getWbUser(request.getSession()).getUserid();

        String state = integralService.exchangeCoupon(userid, couponid, 1);
        Map<String, Object> map = new HashMap<>();
        map.put("status", state);

        //查询我的积分
        JdataBean myIntegral = integralService.queryUserIntegrals(userid);
        map.put("myIntegral", myIntegral.getDataMap());

        json.putData(map);
        return json.toString();
    }

    @RequestMapping(value = "sign")
    public void Sign(HttpServletResponse response, HttpSession session) {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean bean = new JdataBean();
            if (WebSession.checkLoginStatus(session)) {
                bean.put("userid", WebSession.getWbUser(session).getUserid());
            }else {
                WebUtils.responseWrite(response, json.toErrorString(this.getClass(), new ClientException(CodeEnum.LoginOut)));
            }
            String userid = WebSession.getUserId(session);
            JdataBean record = userService.queryToday(userid);
            if (record == null) {
                //查询积分规则
                JdataBean rule = integralService.getIntegralRules();
                List<Integer> days = (List<Integer>) rule.get("days");
                Map<Integer, Integer> days_integrals = (Map<Integer, Integer>)rule.get("days_integrals");
                JdataBean sign = userService.getquerywbsign(userid);
                int signcount = 0;
                int integral = rule.getInt("integral_today");
                if (sign != null) {
                    signcount = sign.getInt("signcount");
                    signcount++;
                    for (int i = 0, size = days.size() ; i < size ; i++) {
                        if (signcount == days.get(i)) {
                            integral += days_integrals.get(days.get(i));
                            break;
                        }
                    }
                    if (signcount == 7) {
                        signcount = 0;
                    }
                }else {
                    signcount++;
                    for (int i = 0, size = days.size() ; i < size ; i++) {
                        if (signcount == days.get(i)) {
                            integral += days_integrals.get(days.get(i));
                            break;
                        }
                    }
                }
                bean.put("platform", 2);//平台
                bean.put("signcount", signcount);//签到次数
                bean.put("integral", integral);//签到积分
                userService.saveSignRecord(bean);
                JdataBean integralData = new JdataBean();
                integralData.put("type", Integral.Type.LOGIN.ordinal());
                integralData.put("content", "签到获得积分");
                integralData.put("platform", 2);
                integralService.updateUserIntegral(userid, String.valueOf(integral), integralData);
            }
            //查询我的积分
            JdataBean myIntegral = integralService.queryUserIntegrals(userid);
            json.putData(myIntegral.getDataMap());

            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 微信签到显示
     * @param response
     * @param session
     */
    @RequestMapping(value = "/signStatus")
    public void signStatus(HttpServletResponse response,HttpSession session){
        JsonReturn json = new JsonReturn();
        try{
            String userId = WebSession.getUserId(session);
            int signcount = 0;
            JdataBean sign = userService.querysigncount(userId);
            Map data = new HashMap();
            if (sign != null) {
                signcount = sign.getInt("signcount");
            }
            data.put("signcount",signcount );
            JdataBean today = userService.queryToday(userId);
            data.put("issign",today != null);
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        }catch (Exception e){
            WebUtils.responseWrite(response,json.toErrorString(this.getClass(),e));
        }
    }

}
